package taskscheduleservicelogic

import (
	"context"
	"github.com/jinzhu/copier"
	"go-zero-admin/application/job/rpc/internal/model"
	"go-zero-admin/pkg/utils"

	"go-zero-admin/application/job/rpc/internal/svc"
	job "go-zero-admin/application/job/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteCronLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteCronLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteCronLogic {
	return &DeleteCronLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 删除定时任务接口
func (l *DeleteCronLogic) DeleteCron(in *job.DeleteCronReq) (*job.DeleteCronRes, error) {
	var mo model.TaskSchedule
	if err := l.svcCtx.DB.Where("id = ?", in.TaskId).First(&mo).Error; err != nil {
		return nil, err
	}

	if err := l.svcCtx.DB.Delete(&model.TaskSchedule{}, in.TaskId).Error; err != nil {
		return nil, err
	}
	var res job.DeleteCronRes
	res.TaskScheduleInfo = &job.TaskScheduleInfo{}
	_ = copier.Copy(&res.TaskScheduleInfo, &mo)
	res.TaskScheduleInfo.CreatedAt = utils.SafeUnix(&mo.CreatedAt)
	res.TaskScheduleInfo.UpdatedAt = utils.SafeUnix(&mo.UpdatedAt)
	res.TaskScheduleInfo.LastExecuteTime = utils.SafeUnix(mo.LastExecuteTime)
	return &res, nil
}
